import axios, { AxiosInstance, AxiosResponse } from 'axios';
import {
  User,
  Order,
  Statistics,
  ApiResponse,
  PaginatedResponse,
  QueryParams,
  LoginResponse,
  UpdateOrderStatusRequest,
  AssignOrderRequest,
  EvaluateOrderRequest,
} from '../types';

class ApiService {
  private api: AxiosInstance;
  private token: string | null = null;

  constructor() {
    this.api = axios.create({
      baseURL: '/api',
      timeout: 30000,
      headers: {
        'Content-Type': 'application/json',
      },
    });

    // 请求拦截器
    this.api.interceptors.request.use(
      (config) => {
        if (this.token) {
          config.headers.Authorization = `Bearer ${this.token}`;
        }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );

    // 响应拦截器
    this.api.interceptors.response.use(
      (response: AxiosResponse<ApiResponse>) => {
        return response;
      },
      (error) => {
        if (error.response?.status === 401) {
          this.logout();
          window.location.href = '/login';
        }
        return Promise.reject(error);
      }
    );

    // 从localStorage恢复token
    this.token = localStorage.getItem('admin_token');
  }

  // 设置token
  setToken(token: string) {
    this.token = token;
    localStorage.setItem('admin_token', token);
  }

  // 清除token
  clearToken() {
    this.token = null;
    localStorage.removeItem('admin_token');
  }

  // 获取token
  getToken(): string | null {
    return this.token;
  }

  // 登录
  async login(phone: string, password: string): Promise<LoginResponse> {
    const response = await this.api.post<ApiResponse<any>>('/auth/login', {
      phone,
      password,
    });
    
    // 检查用户角色 - 修复数据结构访问
    if (response.data.success && response.data.data.role !== 'admin') {
      throw new Error('只有管理员可以访问后台系统');
    }
    
    // 设置token - 修复数据结构访问
    if (response.data.success && response.data.data.token) {
      this.setToken(response.data.data.token);
    }
    
    // 返回适配后的数据结构
    return {
      user: response.data.data,  // 将整个data作为user
      token: response.data.data.token
    };
  }

  // 退出登录
  async logout(): Promise<void> {
    try {
      await this.api.post('/auth/logout');
    } catch (error) {
      console.warn('Logout API error:', error);
    } finally {
      this.clearToken();
    }
  }

  // 获取当前用户信息
  async getCurrentUser(): Promise<User> {
    const response = await this.api.get<ApiResponse<User>>('/auth/me');
    return response.data.data;
  }

  // 获取统计数据
  async getStatistics(): Promise<Statistics> {
    const response = await this.api.get<ApiResponse<Statistics>>('/statistics');
    return response.data.data;
  }

  // 获取工单列表
  async getOrders(params: QueryParams = {}): Promise<PaginatedResponse<Order>> {
    const response = await this.api.get<ApiResponse<PaginatedResponse<Order>>>('/orders', {
      params,
    });
    return response.data.data;
  }

  // 获取单个工单
  async getOrder(orderId: string): Promise<Order> {
    const response = await this.api.get<ApiResponse<Order>>(`/orders/${orderId}`);
    return response.data.data;
  }

  // 更新工单状态
  async updateOrderStatus(
    orderId: string,
    data: UpdateOrderStatusRequest
  ): Promise<Order> {
    const response = await this.api.put<ApiResponse<Order>>(
      `/orders/${orderId}/status`,
      data
    );
    return response.data.data;
  }

  // 分配工单
  async assignOrder(orderId: string, data: AssignOrderRequest): Promise<Order> {
    const response = await this.api.put<ApiResponse<Order>>(
      `/orders/${orderId}/assign`,
      data
    );
    return response.data.data;
  }

  // 评价工单
  async evaluateOrder(orderId: string, data: EvaluateOrderRequest): Promise<Order> {
    const response = await this.api.put<ApiResponse<Order>>(
      `/orders/${orderId}/evaluate`,
      data
    );
    return response.data.data;
  }

  // 删除工单
  async deleteOrder(orderId: string): Promise<void> {
    await this.api.delete(`/orders/${orderId}`);
  }

  // 获取用户列表
  async getUsers(params: QueryParams = {}): Promise<PaginatedResponse<User>> {
    const response = await this.api.get<ApiResponse<PaginatedResponse<User>>>('/users', {
      params,
    });
    return response.data.data;
  }

  // 获取维修员列表
  async getMaintainers(): Promise<User[]> {
    const response = await this.api.get<ApiResponse<PaginatedResponse<User>>>('/users', {
      params: { role: 'maintainer' },
    });
    return response.data.data.items;
  }

  // 更新用户状态
  async updateUserStatus(userId: string, isActive: boolean): Promise<User> {
    const response = await this.api.put<ApiResponse<User>>(`/users/${userId}/status`, {
      isActive,
    });
    return response.data.data;
  }

  // 文件上传
  async uploadFile(file: File, type: string = 'attachment'): Promise<string> {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('type', type);

    const response = await this.api.post<ApiResponse<{ url: string }>>(
      '/upload',
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      }
    );
    return response.data.data.url;
  }
}

export const apiService = new ApiService();
export default apiService;